/**
 * Copyright (c) 2016 Lenovo Group
 * All Rights Reserved.
 * 
 * Project Name:app-gateway
 * Create Time: 2016年2月24日 下午3:49:56
 */
package com.lenovo.lmrp.server.appgateway.spi;

import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

import javax.ws.rs.Consumes;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.lenovo.lmrp.api.appgateway.IAppEngineer;
import com.lenovo.lmrp.api.constant.BizErrorCode;
import com.lenovo.lmrp.api.itsmgateway.IItsmEngineer;
import com.lenovo.lmrp.api.model.RestResponse;
import com.lenovo.lmrp.api.model.entity.EngineerTracePO;
import com.lenovo.lmrp.api.model.view.EngineerPositionVO;
import com.lenovo.lmrp.api.model.view.EngineerVO;
import com.lenovo.lmrp.base.event.EventCode;
import com.lenovo.lmrp.base.event.EventContent;
import com.lenovo.lmrp.base.event.EventSource;
import com.lenovo.lmrp.base.event.EventTopic;
import com.lenovo.lmrp.server.appgateway.AppSession;
import com.lenovo.lmrp.server.appgateway.RestClientFactory;
import com.lenovo.lmrp.server.appgateway.util.AppCache;
import com.lenovo.lmrp.server.appgateway.util.AppMQClient;
import com.lenovo.sdc.framework.annotation.RestService;
import com.lenovo.sdc.framework.cache.CacheItem;
import com.lenovo.sdc.framework.rest.RestClientProxy;
import com.lenovo.sdc.framework.util.CommonUtil;
import com.lenovo.sdc.framework.util.JSONHelper;
import com.lenovo.sdc.framework.util.exception.ErrorCode;
import com.lenovo.sdc.framework.util.exception.TraceableException;

/**
 * @author zhangzhenga
 *
 */
@RestService
@Path("/app/v1")
@Produces("application/json;charset-utf-8")
@Consumes("application/json;charset-utf-8")
public class AppEngineerImpl implements IAppEngineer {

    private static final Logger logger = LoggerFactory.getLogger(AppEngineerImpl.class);

    private AppSession appsession;
    private String token;

    @HeaderParam("Authorization")
    private void setToken(String authorization) {
        if (!CommonUtil.isNullOrEmpty(authorization)) {
            token = authorization.substring(6);
            CacheItem<AppSession> cache = AppCache.getClient().get(AppSession.class, token);
            appsession = cache.getValue();
        }
    }

    /* (non-Javadoc)
     * @see com.lenovo.lmrp.api.appgateway.IAppEngineer#getEngineer(java.lang.String, java.lang.String)
     */
    @Override
    public RestResponse<EngineerVO> getEngineer(String itsmcode, String engineerid) {
    	RestResponse<EngineerVO> result = null;
    	try {
    		RestClientProxy itsmProxy = RestClientFactory.getItsmGatewayClient();
            IItsmEngineer engineerProxy = itsmProxy.getService(IItsmEngineer.class);
            Response response = engineerProxy.getEngineer(itsmcode, engineerid);
            if (response.getStatus() == 200) {
            	RestResponse<?> restResponse = response.readEntity(RestResponse.class);
            	EngineerVO engineerVO = JSONHelper.convertToObject(restResponse.getResult(), EngineerVO.class);
            	result = new RestResponse<EngineerVO>(engineerVO);
            }
		} catch (Exception e) {
			TraceableException.writeLog(BizErrorCode.APPGW_ITSMGW_ERROR, "get engineer failed.", e);
			return new RestResponse<EngineerVO>(1, "get engineer failed", null);
		}
    	return result;
    }

    /* (non-Javadoc)
     * @see com.lenovo.lmrp.api.appgateway.IAppEngineer#setEngineerStatus(java.lang.String, java.lang.String, int)
     */
    @Override
    public RestResponse<Integer> setEngineerStatus(String itsmcode, String engineerid, int status) {
        //调用ITSM修改工程师信息接口
        RestClientProxy itsmProxy = RestClientFactory.getItsmGatewayClient();
        IItsmEngineer engineer = itsmProxy.getService(IItsmEngineer.class);
        EngineerVO engineerVO = new EngineerVO();
        engineerVO.setStatus(status);
        RestResponse<Integer> response = engineer.updateEngineer(itsmcode, engineerid, engineerVO);
        return response;
    }

    /* (non-Javadoc)
     * @see com.lenovo.lmrp.api.appgateway.IAppEngineer#setEngineerInfo(java.lang.String, java.lang.String, java.util.Map)
     */
    @Override
    public RestResponse<Integer> setEngineerInfo(String itsmcode, String engineerid, Map<String, String> fields) {

        RestClientProxy itsmProxy = RestClientFactory.getItsmGatewayClient();
        IItsmEngineer engineer = itsmProxy.getService(IItsmEngineer.class);
        EngineerVO engineerVO = new EngineerVO();
        engineerVO.setStatus(-1);
        engineerVO.setEngineerid(engineerid);
        engineerVO.setLoginname(engineerid);
        boolean modifyPwd = false;
        if (Objects.nonNull(fields)) {
            String password = fields.get("password");
            //修改密码
            if (CommonUtil.nonNullAndEmpty(password)) {
                modifyPwd = true;
                String paswordOld = password.substring(0, password.indexOf(":"));
                String passwordNew = password.substring(password.indexOf(":") + 1);
                //解码
                byte[] oldPwdBytes = Base64.getDecoder().decode(paswordOld);
                byte[] oldPwdBytesFinal = Base64.getDecoder().decode(oldPwdBytes);
                String oldPassword = new String(oldPwdBytesFinal);
                engineerVO.setOldPassword(oldPassword);

                byte[] newPwdBytes = Base64.getDecoder().decode(passwordNew);
                byte[] newPwdBytesFinal = Base64.getDecoder().decode(newPwdBytes);
                String newPassword = new String(newPwdBytesFinal);
                engineerVO.setPasswd(newPassword);
            }
            if (CommonUtil.nonNullAndEmpty(fields.get("phone"))) {
                engineerVO.setPhone(fields.get("phone"));
            }
            if (CommonUtil.nonNullAndEmpty(fields.get("email"))) {
                engineerVO.setPhone(fields.get("email"));
            }
            //更新itsm系统的用户信息
            RestResponse<Integer> itsmResponse = engineer.updateEngineer(itsmcode, engineerid, engineerVO);

            return itsmResponse;
        }
        return new RestResponse<Integer>(1, "数据提交错误", 1);
    }

    /* (non-Javadoc)
     * @see com.lenovo.lmrp.api.appgateway.IAppEngineer#getSecurityCode(java.lang.String, java.lang.String)
     */
    @Override
    public RestResponse<Integer> getSecurityCode(String itsmcode, String loginName) {
        // TODO Auto-generated method stub
        return null;
    }

    /* (non-Javadoc)
     * @see com.lenovo.lmrp.api.appgateway.IAppEngineer#resetPassword(java.lang.String, java.lang.String, java.lang.String)
     */
    @Override
    public RestResponse<Integer> resetPassword(String itsmcode, String loginName, String securityCode) {
        // TODO Auto-generated method stub
        return null;
    }

    /* (non-Javadoc)
     * @see com.lenovo.lmrp.api.appgateway.IAppEngineer#setEngineerPosition(java.lang.String, java.lang.String, java.lang.String)
     */
    @Override
    public RestResponse<Integer> setEngineerPosition(String itsmcode, String engineerid,
                                                     EngineerPositionVO positionVO) {
        try {
            if (positionVO != null) {
                logger.debug("engineer {} upload position info is action:{},lnt:{},lat:{},address:{}", engineerid,
                    positionVO.getAction(), positionVO.getLongitude(), positionVO.getLatitude(),
                    positionVO.getAddress());
                //创建mq消息
                EventContent<EngineerTracePO> content = new EventContent<>();
                content.setCode(EventCode.ENGINEER_TRACE);
                content.setSource(EventSource.APPGW);
                EngineerTracePO tracePO = new EngineerTracePO();
                tracePO.setAction(positionVO.getAction());
                tracePO.setEngineerId(engineerid);
                tracePO.setItsmCode(itsmcode);
                tracePO.setAddress(positionVO.getAddress());
                tracePO.setLatitude(positionVO.getLatitude());
                tracePO.setLongitude(positionVO.getLongitude());
                tracePO.setTraceTime(new Date());
                Map<String, String> poContent = new HashMap<>();
                poContent.put("appversion", positionVO.getAppversion());
                tracePO.setContent(poContent);
                
                content.setContent(tracePO);
                AppMQClient.getMQClient().publish(EventTopic.ENGINEER_EVENT.name(), JSONHelper.toJSON(content));
                logger.debug("position sended by mq. mqcontent is {}", JSONHelper.toJSON(content));
            }
            else {
                return new RestResponse<Integer>(1, "position info is null", null);
            }
        }
        catch (Exception exp) {
            TraceableException.writeLog(ErrorCode.MQ_ERROR, "send engineer position failed", exp);
            return new RestResponse<Integer>(1, "failed", null);
        }
        return new RestResponse<Integer>(0, "ok", null);
    }
}
